<template>
  <el-upload class="upload-demo" :show-file-list="false" action :accept="accept" :on-exceed="handleExceed"
    :maxSize="maxSize" :http-request="upload" :before-upload="beforeUpload">
    <el-button type="primary" size="small" v-if="type == 'file'">上传文件</el-button>
    <div class="upload" v-if="type == 'img'"><i class="el-icon-plus"></i></div>
    <div class="upload-tooltip" v-if="size.length > 0 && accept == 'image/*'">
      建议尺寸：{{ size[0] }} * {{ size[1] }}
    </div>
    <div class="upload-tooltip" v-if="size.length > 0 && accept != 'image/*'">
      图片尺寸：{{ size[0] }} * {{ size[1] }}
    </div>
  </el-upload>
</template>
<script>
import BMF from 'browser-md5-file'
const bmf = new BMF()
export default {
  name: 'upload',
  props: {
    type: {
      //文件类型
      type: String,
      default: () => {
        return 'img'
      },
    },
    accept: {
      //文件类型
      type: String,
      default: () => {
        return ''
      },
    },
    maxSize: {
      //文件大小 MB
      type: String,
      default: () => {
        return '20'
      },
    },
    size: {
      //图片尺寸  仅图片可用
      type: Array,
      default: () => {
        return []
      },
    },
  },
  data() {
    return {
      form: {},
      md5: '',
    }
  },
  methods: {
    upload(e) {
      //上传文件
      bmf.md5(e.file, (err, md5) => {
        //计算md5值
        this.md5 = md5
      })
      this.oosUpload(e.file)
      //上传文件
      let formData = new FormData();
      formData.append("file", file.file);
      this.$axios.post("/admin/file/upload", formData).then((data) => {
        if (data.code == 200) {
          this.$message.success("操作成功");
          this.$emit("upload", data.data);
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    beforeUpload(file) {
      //判断文件大小
      let $this = this
      if (this.maxSize && !(file.size / 1024 / 1024 < this.maxSize)) {
        this.$message.error('文件大小不能超过 ' + this.maxSize + 'MB!')
        return false
      }
      //判断图片尺寸
      if (this.size.length > 0 && this.accept != 'image/*') {
        let img
        const isSize = new Promise(function (resolve, reject) {
          img = new Image()
          img.src = URL.createObjectURL(file)
          img.onload = function () {
            let valid =
              img.width == $this.size[0] && img.height == $this.size[1]
            valid ? resolve() : reject()
          }
        }).then(
          () => {
            return file
          },
          () => {
            $this.$message.error(
              '图片尺寸应该为：' + $this.size[0] + '*' + $this.size[1]
            )
            return Promise.reject()
          }
        )
        return isSize
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 ${this.limit} 个文件，本次选择了 ${files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    oosUpload(file, name) {
      let that = this
      //目录
      let catalog = name || 'public'
      //日期年月日
      const now = new Date()
      const year = now.getFullYear() // 获取当前年份，例如：2023
      const month = now.getMonth() + 1 // 获取当前月份（注意月份是从0开始计数的）
      const day = now.getDate() // 获取当前日期
      const time = new Date().getTime()
      let date = `${year}${month > 9 ? month : '0' + month}${day > 9 ? day : '0' + day
        }-${time}`
      //返回对象
      let obj = {
        id: file.uid,
        name: file.name,
        type: file.type,
        size: file.size,
        fileDomain: '',
        url: '',
      }
      this.$axios
        .get('/admin/upload/getSTS', { showLoading: true })
        .then((data) => {
          if (data.code == 200) {
            let loading = this.$loading({
              lock: true,
              text: '上传中请等待...',
              background: 'rgba(0, 0, 0, 0.7)',
            })

            obj.fileDomain = data.data.endPoint
            obj.url = `/${data.data.buketName}/${catalog}/${date}/${file.name}`
            const s3Config = {
              accessKeyId: data.data.accessKeyId,
              secretAccessKey: data.data.secretAccessKey,
              endpoint: data.data.endPoint.substring(
                data.data.endPoint.indexOf('//') + 2
              ),
              sessionToken: data.data.sessionToken,
              signatureVersion: 'v4', // 可选v2 或v4
              apiVersion: '2006-03-01',
              s3ForcePathStyle: true,
            }
            const client = new OOS.S3(s3Config)
            client.putObject(
              {
                Body: file,
                Bucket: data.data.buketName,
                Key: `${catalog}/${date}/${file.name}`,
              },
              function (err, data) {
                loading.close()
                if (err) {
                  that.$message.error('操作失败！')
                } else {
                  that.$message.success('操作成功！')
                  that.$emit('upload', obj, that.md5)
                }
              }
            )
          } else {
            this.$message.error(data.msg)
          }
        })
    },
  },
}
</script>

<style lang="scss" scoped>
.upload {
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
  border: 1px dashed #d9d9d9;

  i {
    font-size: 20px;
    color: #8c939d;
  }
}

.upload-tooltip {
  line-height: initial;
  padding-top: 5px;
  font-size: 10px;
  color: #8c939d;
}
</style>
